package com.jtech.together.view.weight;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;

import com.jtech.together.R;
import com.jtech.together.model.event.ReceiveMessageEvent;
import com.jtech.together.util.Bus;
import com.jtech.together.util.IM;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.newim.bean.BmobIMAudioMessage;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMImageMessage;
import cn.bmob.newim.bean.BmobIMLocationMessage;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMTextMessage;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.exception.BmobException;
import cn.dreamtobe.kpswitch.util.KPSwitchConflictUtil;
import cn.dreamtobe.kpswitch.util.KeyboardUtil;
import cn.dreamtobe.kpswitch.widget.KPSwitchPanelFrameLayout;

/**
 * 聊天输入框
 * Created by wuxubaiyang on 2017/5/14.
 */

public class ChatInputView extends CardView implements TextWatcher, RecordKeyboard.OnRecordKeyboardListener,
        KeyboardUtil.OnKeyboardShowingListener, KPSwitchConflictUtil.SwitchClickListener, EmojiKeyboard.OnEmojikeyboardListener {
    @Bind(R.id.edittext_chat_input)
    EditText editTextInput;
    @Bind(R.id.imagebutton_chat_input_send)
    ImageButton imageButtonSend;
    @Bind(R.id.imagebutton_chat_input_mic)
    ImageButton imageButtonMic;
    @Bind(R.id.imagebutton_chat_input_emoji)
    ImageButton imageButtonEmoji;
    @Bind(R.id.emojikeyboard_chat_input)
    EmojiKeyboard emojiKeyboard;
    @Bind(R.id.recordkeyboard_chat_input)
    RecordKeyboard recordKeyboard;
    @Bind(R.id.panellayout_chat_input)
    KPSwitchPanelFrameLayout switchPanelLayout;

    private InputMethodManager inputMethodManager;
    private ChatInputListener chatInputListener;
    private IM im;

    public ChatInputView(Context context) {
        this(context, null);
    }

    public ChatInputView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChatInputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化视图
        init();
    }

    /**
     * 初始化视图
     */
    private void init() {
        //实例化键盘管理
        this.inputMethodManager = (InputMethodManager)
                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        //实例化主视图
        View contentView = LayoutInflater.from(getContext())
                .inflate(R.layout.view_chat_input, this, false);
        //设置主视图
        addView(contentView);
        //绑定视图
        ButterKnife.bind(this, contentView);
        //设置发送按钮为不可用
        imageButtonSend.setEnabled(false);
        //输入框与表情键盘绑定
        emojiKeyboard.setupTargetInput(editTextInput);
        //设置录音键盘监听
        recordKeyboard.setOnRecordKeyboardListener(this);
        //添加文本输入监听
        editTextInput.addTextChangedListener(this);
        //设置表情键盘监听
        emojiKeyboard.setOnEmojikeyboardListener(this);
    }

    /**
     * 依附
     *
     * @param activity
     */
    public void attach(Activity activity) {
        //监控键盘状态
        KeyboardUtil.attach(activity, switchPanelLayout, this);
        //处理面板与键盘
        KPSwitchConflictUtil.attach(switchPanelLayout, editTextInput, this,
                new KPSwitchConflictUtil.SubPanelAndTrigger(recordKeyboard, imageButtonMic),
                new KPSwitchConflictUtil.SubPanelAndTrigger(emojiKeyboard, imageButtonEmoji));
    }

    /**
     * 监听后退操作
     *
     * @return
     */
    public boolean onBackPressed() {
        if (switchPanelLayout.getVisibility() == VISIBLE) {
            switchPanelLayout.setVisibility(GONE);
            imageButtonEmoji.setSelected(false);
            imageButtonMic.setSelected(false);
            return false;
        }
        return true;
    }

    /**
     * 设置聊天控制监听
     *
     * @param chatInputListener
     */
    public void setChatInputListener(ChatInputListener chatInputListener) {
        this.chatInputListener = chatInputListener;
    }

    /**
     * 设置会话
     *
     * @param conversation
     */
    public void setConversation(BmobIMConversation conversation) {
        this.im = IM.build(conversation);
    }

    /**
     * 发送文本消息
     *
     * @param text
     */
    public void sendTextMessage(String text) {
        BmobIMTextMessage imTextMessage = new BmobIMTextMessage();
        imTextMessage.setContent(text);
        sendMessage(imTextMessage);
    }

    /**
     * 发送录音消息
     *
     * @param localPath
     */
    public void sendAudioMessage(String localPath) {
        sendMessage(new BmobIMAudioMessage(localPath));
    }

    /**
     * 发送图片消息
     *
     * @param localPath
     */
    public void sendPhotoMessage(String localPath) {
        sendMessage(new BmobIMImageMessage(localPath));
    }

    /**
     * 发送位置消息
     *
     * @param la
     * @param lo
     * @param address
     */
    public void sendLocationMessage(double lo, double la, String address) {
        sendMessage(new BmobIMLocationMessage(address, la, lo));
    }

    /**
     * 发送消息
     *
     * @param imMessage
     */
    public void sendMessage(BmobIMMessage imMessage) {
        if (null != im) {
            im.sendMessage(imMessage, new MessageSendListener() {
                @Override
                public void done(BmobIMMessage bmobIMMessage, BmobException e) {

                }
            });
            //消息接收
            Bus.get().post(new ReceiveMessageEvent(imMessage));
        }
    }

    /**
     * 设置权限
     *
     * @param activity
     */
    public void setupPermission(Activity activity) {
        recordKeyboard.setupPermission(activity);
    }

    /**
     * 操作点击
     *
     * @param v
     */
    @OnClick({R.id.imagebutton_chat_input_photo, R.id.imagebutton_chat_input_location, R.id.imagebutton_chat_input_send})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imagebutton_chat_input_photo://发送图片
                if (null != chatInputListener) {
                    chatInputListener.acquirePhoto();
                }
                break;
            case R.id.imagebutton_chat_input_location://发送位置
                if (null != chatInputListener) {
                    chatInputListener.acquireLocation();
                }
                break;
            case R.id.imagebutton_chat_input_send://发送按钮
                String content = editTextInput.getText().toString();
                sendTextMessage(content);
                editTextInput.setText("");
                break;
        }
    }

    @Override
    public void onKeyboardShowing(boolean isShowing) {
        if (null != chatInputListener) {
            chatInputListener.panelOrKeyboardChange(isShowing);
        }
        if (isShowing) {
            imageButtonEmoji.setSelected(false);
            imageButtonMic.setSelected(false);
        }
    }

    @Override
    public void onClickSwitch(boolean switchToPanel) {
        if (null != chatInputListener) {
            chatInputListener.panelOrKeyboardChange(switchToPanel);
        }
    }

    @Override
    public void onEmojiVisibilityChange(boolean isVisibility) {
        imageButtonEmoji.setSelected(isVisibility);
    }

    @Override
    public void onRecordVisibilityChange(boolean isVisibility) {
        imageButtonMic.setSelected(isVisibility);
    }

    @Override
    public void recordSuccess(File file) {
        sendAudioMessage(file.getAbsolutePath());
        //关闭panel
        switchPanelLayout.setVisibility(GONE);
        //设置录音按钮
        imageButtonMic.setSelected(false);
    }

    @Override
    public void recordFail(String error) {
        Snackbar.make(editTextInput, error, Snackbar.LENGTH_SHORT).show();
        //关闭panel
        switchPanelLayout.setVisibility(GONE);
        //设置录音按钮
        imageButtonMic.setSelected(false);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //设置发送按钮是否可点击
        imageButtonSend.setEnabled(s.length() > 0);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    /**
     * 聊天控制监听
     */
    public interface ChatInputListener {
        void acquirePhoto();

        void acquireLocation();

        void panelOrKeyboardChange(boolean isShowing);
    }
}